<?php
namespace control;

// 模具入库
class moldInStockClass extends adIndexClass
{
	private const page        = 'moldInStock';
	private const table       = 'mold_inventory';
	private const tableMx     = 'mold_inventory_detail';
	private const tableRecord = 'mold_inventory_record';
	private const tableTarget = 'mold';
	private const title       = '模具入库';
	private const state       = ['制单', '待确认', '已确认'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => "入库单号",
                        'width' => 250,
                        'sort' => 1,
                    ],
                    'supplier'  => [
                        'name'  => '供应商名称',
                        'width' => 250,
                    ],
                    'warehouse'         => [
                        'name'  => '仓库名称',
                        'width' => 250,
                    ],
                    'stid'          => [
                        'name'  => '制单人',
                        'width' => 250,
                    ],
                    'orderDate'          => [
                        'name'  => '入库日期',
                        'width' => 250,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 250,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "入库单号"   => text(array("name" => "orderNo")),
                    "供应商"   => selectMultiple(["name" => "targetId", 'table' => "supplier", 'sqlId' => 'id', 'where' => "coid = '" . self::$coid . "'", 'sqlField' => 'name']),
                    "仓库名称" => selectMultiple(["name" => "warehouseId", 'table' => "warehouse", 'sqlId' => 'id', 'where' => "coid = '" . self::$coid . "'", 'sqlField' => 'name']),
                ],
                [
                    "制单人"   => selectMultiple(["name" => "stid", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name']),
                    "入库日期" => text(['name' => 'orderDate', 'laydate' => ['range' => '~', 'type' => 'date'],]),
                    "状态" => select(["name" => "state", 'option' => self::state]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/**
	 * 列表-查询条件
	 *
	 * @return string
	 */
	public function home(): string
	{
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url     = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        if ($this->power(self::page, "print")) {
            $button .= " <span onclick=\"batchPrint('" . $this->get('cla') . "')\" class='spanButton'>批量打印</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

	/**
	 * 客户列表-查询结果
	 *
	 * @return bool|string
	 */
	public function homeSearch(): string
	{
		//查询结果
		$equal = [
			'targetId'    => $this->post('targetId'),
			'warehouseId' => $this->post('warehouseId'),
			'stid'        => $this->post('stid'),
			'state'       => $this->post('state'),
			'coid'        => self::$coid,
		];
		$like  = [
			'orderNo' => $this->post('orderNo'),
		];
		//生成查询语句
		$where = search([
			"="    => $equal,
			"like" => $like,
		]);

		if ($this->post('orderDate')) {
			$where .= self::timeComparison($this->post('orderDate'), 'date', 'orderDate');
		}
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		$page = $this->page(["table" => self::table, "where" => $where, "order" => $orderBy['orderBy']]);
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		//获取记录
		$url     = root . "control/adIndex.html?cla=" . self::page;
		$isPrint = $this->power(self::page, "print") ? true : false;
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate  = array(
				"box"    => ["name" => "listId", "value" => $array['id']],
				"detail" => ["title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"],
				"edit"   => $array['state'] !== '已确认' ? ["title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"] : [],
				'print'  => ($isPrint === true) ? ['title' => '打印', 'click' => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$array['id']}')"] : [],
			);
			$supplier  = query('supplier', " id = '$array[targetId]' ");
			$warehouse = query('warehouse', " id = '$array[warehouseId]' ");
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'supplier':
                        $row[] = supplierClass::getName($array['targetId']);
                        break;
                    case 'warehouse':
                        $row[] = warehouseClass::getName($array['warehouseId']);
                        break;
                    case 'stid':
                        $row[] = self::findStaff($array['stid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
		//控件
		$button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
		//返回
		$json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}
    /**
     * 保存并提交
     * @return bool|string
     */
    public function saveAndCommit(): bool|string
    {
        $resultJson = $this->editEdit();
        $result = json_decode($resultJson,true);
        if ($result['warn'] == 2){
            unset($_SESSION['warn']);
            $resultJson = $this->commitEdit();
        }
        return $resultJson;
    }

	/**
	 * 编辑页
	 *
	 * @return string
	 */
	public function edit(): string
	{
		$id       = $this->get('id');
		$info     = query(self::table, " coid = '" . self::$coid . "' AND id = '" . $id . "' ");
		$button[] = [
			'style' => 'li-btn-blue-bg',
			"name"  => "保存",
			"type"  => "点击事件",
			"title" => "保存",
			'fun'   => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
		];
        $button[] = [
            "name" => "保存并提交",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=saveAndCommit')"
        ];
		$tr[]     = ['', '编码', '模具名称', '规格', '数量', '单价（' . static::$unit . '）', '金额（' . static::$unit . '）', '备注'];

		$result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by time"));
		foreach ((array)$result['array'] as $k=>$array) {
			$mold = query('mold', " id = '$array[mdid]'  ");
			$tr[] =
				[
                    componentClass::tablePperation($k+1,"delTableRow(this)").
					hidden(['name' => 'mxId[]', 'value' => $array['id']]) .
					hidden(['name' => 'mdid[]', 'value' => $array['mdid'],]),
					$mold['code'], $mold['name'], $mold['model'],
					text(['name' => 'num[]', 'other' => self::digitalFiltering('numPrecision'), 'value' => self::lostZero($array['num'],'numPrecision'), 'blur' => 'countMoney',]),
					text(['name' => 'price[]', 'other' => self::digitalFiltering('pricePrecision'), 'value' => self::lostZero($array['price'],'pricePrecision'), 'blur' => 'countMoney',]),
					"<span class='total'>" . self::formattingFigure($array['num'] * $array['price']) . "</span>",
					text(['name' => 'mxText[]', 'value' => $array['text'],]),
				];
		}
		$list  = $this->listTable(array('tr' => $tr, 'end' => true));
		$page  = self::page;
        $tableBut = <<<EOT
                <span class="smallButton" onclick="layer('{$this->get('cla')}','addMx', $('form[name={$page}EditForm]').serialize())">选择模具</span>
EOT;
		//表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . '供应商'  => selectMultiple(['table' => 'supplier', "title" => '供应商', 'where' => " coid = '" . self::$coid . "' ", 'sqlField' => 'name', 'sqlId' => 'id', 'name' => 'targetId', 'value' => $info['targetId'], 'change' => 'assign']),
                    must . '仓库名称' => selectMultiple(['table' => 'warehouse', "title" => '仓库名称', 'where' => " coid = '" . self::$coid . "' AND state = '启用' ", 'sqlField' => 'name', 'sqlId' => 'id', 'name' => 'warehouseId', 'value' => $info['warehouseId'], 'change' => 'assign']),
                    must . '入库日期' => text(['name' => "orderDate", 'class' => 'text', 'value' => $info['orderDate'] ?: $this->date, 'laydate' => [],]),
                ],
                [
                    '备注' => textarea(['name' => "text", 'class' => 'text', 'value' => $info['text']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => '选择明细',
            'button' => $tableBut,
            'html' => $list,
        ]);
		$data['html'] = $this->pageEdit([
			"html"  => $body,
			'hidden' => hidden(['name' => 'id', 'value' => $id]),
		]);
		$data['html'] .= <<<EOT
<script>
//计算金额，税额等
function countMoney(that){
    const obj = $(that).parent().parent('tr'),
    	  num = obj.find('[name="num[]"]').val(),
    	  price = obj.find('[name="price[]"]').val()
    let total = (num * price).toFixed(amountPrecision)
    obj.find(".total").html(total)
}
function addRow(){
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit', $("form[name='mxForm']").serialize(),function(res) {
        $("#materialTable tbody").append(res.html);
        resetNumber($("#materialTable"))
    },'json');
}

function assign(e) {
    let val = $(e).find("option:selected").text()
    let name = $(e).attr('name').replace('Id', '')
    $("[name="+name+"]").val(val);
}
</script>
EOT;
		//返回
		return $this->tab($data);
	}

	/**
	 * 编辑报错
	 *
	 * @return bool|string
	 */
	public function editEdit(): bool|string
	{
		$id        = $this->post('id') ?: self::getId();
		$mxIdArr   = $this->post('mxId') ?: [];
		$mdidArr   = $this->post('mdid');
		$priceArr  = $this->post('price');
		$numArr    = $this->post('num');
		$mxTextArr = $this->post('mxText');

		$field      = [
			'targetId'    => $this->post('targetId'),
			'warehouseId' => $this->post('warehouseId'),
			'orderDate'   => $this->post('orderDate'),
			'text'        => $this->post('text'),
		];
		$annotation = [
			'targetId'    => '供应商',
			'warehouseId' => '仓库',
			'orderDate'   => '入库日期',
			'text'        => '备注',
		];
		$rules      = [
			'targetId'    => 'required',
			'warehouseId' => 'required',
			'orderDate'   => 'required',
		];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
			goto resp;
		}
		$where = " id = '$id' ";
		$info  = query(self::table, $where);
		//判断
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = "你没有编辑" . self::title . "的权限";
		} elseif (static::is_null_array($mxIdArr)) {
			$json['warn'] = '请选择入库明细';
		} elseif (static::is_null_array($mdidArr)) {
			$json['warn'] = '请选择入库明细';
		} elseif (static::is_null_array($numArr)) {
			$json['warn'] = '数量请填写完整';
		} elseif (!empty($info['id']) && $info['state'] == '已确认') {
			$json['warn'] = '此入库单已确认，不能修改';
		} else {
			$this->startTrans();
			$isPass = true;//事务通过标志
			if (!$info['id']) {
				$orderNo      = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'OSIN' . date('Ymd'),
                    'table'  => self::table,
                    'field'  => 'orderNo',
                    'where'  => " AND coid = '" . self::$coid . "' ",
                ],$field);
				$field        = array_merge($field, [
					'id'      => $id,
					'orderNo' => $orderNo,
					'state'   => '制单',
					'coid'    => self::$coid,
					'stid'    => $this->control['stid'],
				]);
				$json['warn'] = static::insert(["table" => self::table, "field" => $field]);
			} else {
				$json['warn'] = static::update([
					"table" => self::table,
					"field" => $field,
					"where" => $where,
				]);
			}
			//添加或更新入库单明细
			foreach ($mxIdArr as $k => $nid) {
				$mx   = query(self::tableMx, "id = '$nid'");
				$mold = query('mold', "id = '$mdidArr[$k]'");
                $numArr[$k] = self::formattingFigure($numArr[$k],'numPrecision');
				if (static::isNull($mold['id'])) {
					continue;
				}
				if (!empty($mx['id'])) {
					//更新
					$warn = static::update([
						"table" => self::tableMx,
						"field" => [
							'mdid'  => $mold['id'],
							'num'   => $numArr[$k],
							'price' => $priceArr[$k],
							'text'  => $mxTextArr[$k],
						],
						"where" => " id = '$nid'",
					]);
				} else {
					//新增
					$warn = static::insert([
						"table" => self::tableMx,
						"field" => [
							'id'      => $nid,
							'coid'    => self::$coid,
							'orderId' => $id,
							'mdid'    => $mold['id'],
							'num'     => $numArr[$k],
							'price'   => $priceArr[$k],
							'text'    => $mxTextArr[$k],
						],
					]);
				}
				if (!in_array($warn, ['新增成功', '更新成功'])) {
					$isPass       = false;
					$json['warn'] = $warn;
					break;
				}
			}
			if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass) {
				$this->commitTrans();
				delete(['table' => self::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"]);
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
			} else {
				$this->rollback();
			}
		}

		resp:
		return json_encode($json, 320);
	}


	/**
	 * @return bool|string
	 */
	public function addMx(): bool|string
	{
		if (static::isNull($this->post('warehouseId'))) {
			return json_encode(['warn' => '请选择仓库', 320]);
		} else {
			$mdidArr = $this->post('mdid') ?: [];
			$html    =
				select(["name" => "type", "title" => "类别", 'option' => explode('，', para(self::page . 'Type'))])
				. text(["name" => "code", "title" => "编码"])
				. text(["name" => "name", "title" => "名称"])
				. text(["name" => "model", "title" => "规格型号"])
				. hidden(["name" => "warehouseId", 'value' => $this->post('warehouseId')])
				. hidden(["name" => "mdid", 'value' => implode(',', $mdidArr)])
				. hidden(['name' => 'orderId', 'value' => $this->post('orderId')]);
			$button  = "<input style='margin-left: 5px' onclick=\"addRow();$('#" . self::page . "AddMx').remove()\" type='button' class='searchSub' value='提交'>";
			$html    = $this->search($html);
			return $this->layer(["title" => "添加", "height" => 600, "width" => 1100, "html" => $html, "button" => $button]);
		}
	}

	/**
	 *添加物料
	 */
	public function addMxSearch(): bool|string
	{
		$mdid  = $this->post('mdid') ? explode(',', $this->post('mdid')) : [];
		$where = " 1=1 and id not in ('" . implode("','", $mdid) . "')";
		// $and     = " AND coid = '" . self::$coid . "' AND id IN (SELECT mdid FROM mold_inventory_record WHERE warehouseId = '" . $this->post('warehouseId') . "' )  ";
		$and   = " AND coid = '" . self::$coid . "' ";
		$like  = [
			'name'  => $this->post('name'),
			'code'  => $this->post('code'),
			'model' => $this->post('model'),
		];
		$equal = [
			'state' => '启用',
			'type'  => $this->post('type'),
		];
		$where .= search(["like" => $like, "=" => $equal]) . $and;
		$page  = $this->page([
			"table"   => "mold",
			"where"   => $where,
			'pageNum' => 50,
			"order"   => " `time` ASC",
		]);
		//获取表头
		$checkAll = $this->checkAll("mxForm", "mxId");
		$tr[]     = [$checkAll, '类别', '编码', '模具名称', '规格'];
		//获取记录
		foreach ($page['array'] as $array) {
			$dominate = [
				"box" => ["name" => "mxId", "value" => $array['id']],
			];
			$tr[]     = [
				$this->dominate($dominate),
				$array['type'],
				$array['code'],
				$array['name'],
				$array['model'],
			];
		}
		$json['html'] = $page['hint'] .
            "<form name='mxForm'>" .
                hidden(['name' => 'warehouseId', 'value' => $this->post('warehouseId')]) .
                $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) .
            "</form>" .
            $page['button'];
		return json_encode($json, 320);
	}

	/**
	 * 编辑
	 *
	 * @return bool|string
	 */
	public function addMxEdit(): bool|string
	{
		$mxIdArr     = $this->post('mxId');
		$warehouseId = $this->post('warehouseId');
		if (!$this->power(self::page, 'edit')) {
			$json['warn'] = '你还没有编辑权限';
		} elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
			$json['warn'] = '请选择物料';
		} else {
			$tr = [];
			foreach ($mxIdArr as $mxId) {
				$mold = query('mold', "id = '$mxId'");
				if (static::isNull($mold['id'])) {
					continue;
				}
				$id           = self::getId();
                $tr[]              = [
                    componentClass::tablePperation('',"delTableRow(this)").
                    hidden(array('name' => 'mxId[]', 'value' => $id)) .
                    hidden(array('name' => 'mdid[]', 'value' => $mold['id'])),
                    $mold['code'],
                    $mold['name'],
                    $mold['model'],
                    text(array('name' => 'num[]', 'blur' => 'countMoney', 'other' => self::digitalFiltering('numPrecision'), 'value' => '')),
                    text(array('name' => 'price[]', 'blur' => 'countMoney', 'other' => self::digitalFiltering('pricePrecision'), 'value' => '')),
                    "<span class='total'>0</span>",
                    text(array('name' => 'mxText[]')),
                ];
			}
            $json['html'] = $this->tableMany(array('tr' => $tr, 'thead' => false));
			$json['warn'] = 2;
		}
		return json_encode($json, 320);
	}

	/**
	 * 详情页
	 *
	 * @return string
	 */
	public function detail(): string
	{
		$info = query(self::table, " coid = '" . self::$coid . "' AND id = '{$this->get('id')}'");
		if (empty($info['id'])) {
			$html = '未找到此' . self::title;
		} else {
			//菜单
			$data = array(
				"id" => $info['id'],
			);

			$button = [];
			if ($this->power(self::page, "edit") && $info['state'] != '已确认') {
				if ($info['state'] == '制单') {
					//按钮
					$button[] = [
						"name"  => "编辑",
						"type"  => "顶部页卡",
						"title" => "编辑用户",
						"url"   => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
						'style' => 'li-btn-blue-bg',
					];
					//按钮
					$button[] = [
						"name" => "提交",
						"type" => "弹出层",
						"cla"  => $this->get('cla'),
						"fun"  => "operate",
						"post" => ["act" => 'commit', "id" => $info['id']],
					];
				}
				//按钮
				$button[] = [
					"name" => "删除",
					"type" => "弹出层",
					"cla"  => $this->get('cla'),
					"fun"  => "operate",
					"post" => ["act" => 'del', "id" => $info['id']],
				];
			}
			if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
				$button[] = [
					"name"  => "确认",
					"type"  => "弹出层",
					"cla"   => $this->get('cla'),
					"fun"   => "operate",
					"post"  => ["act" => 'confirm', "id" => $info['id']],
					'style' => 'li-btn-blue-bg',
				];
			}
			if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
				$button[] = [
					"name" => "取消",
					"type" => "弹出层",
					"cla"  => $this->get('cla'),
					"fun"  => "operate",
					"post" => ["act" => 'cancel', "id" => $info['id']],
				];
			}
			//操作记录
            $button[] = self::operateLogBut($info['id']);

			$mxtr[] = ['编码', '模具名称', '规格', '数量', '单价（元）', '金额（元）', '备注'];
			$result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by time"));
			foreach ($result['array'] as $array) {
				$mold   = query('mold', " id = '$array[mdid]'");
				$mxtr[] = [
					$mold['code'],
					$mold['name'],
					$mold['model'],
					self::lostZero($array['num'],'numPrecision'),
                    self::lostZero($array['price'],'pricePrecision'),
					self::formattingFigure($array['num'] * $array['price']),
					$array['text'],
				];
			}
			$res  = find(['table' => self::tableMx, 'field' => " IFNULL(sum(num), 0) as num, IFNULL(sum(num*price), 0) as total", 'single' => "orderId = '$info[id]' group by orderId",]);
			$nums = $total = 0;
			if (!static::isNull($res)) {
				$nums  = self::lostZero($res['num'],'numPrecision');
				$total = self::lostZero($res['total']);
			}
            $total_tr = [
                3 => $nums,
                5 => $total,
            ];
			//生成表单
            $data['button'] = $this->tableShowButton($button);
			$data['html'] = $this->tableShow([
				[
					[
						"供应商名称" => query('supplier', " id = '{$info['targetId']}' ", 'name')['name'],
						"仓库名称"  => query('warehouse', " id = '{$info['warehouseId']}' ", 'name')['name'],
						"单据日期"  => $info['orderDate'],
                        "入库单号" => $info['orderNo'],
					],
                    [
                        "制单人"  => self::findStaff($info['stid']),
                        "状态"   => $info['state']
                    ],
					[
						"备注" => pre($info['text']),
					],

				],
			]);
            $data['html'] .= $this->detailList([
                'title' => '入库明细',
                'html' => $this->listTable(['tr' => $mxtr, 'showEmpty' => true, 'total' => $total_tr, 'showSort' => true]),
            ]);
			//生成页面
			$html = $this->tab($data);
		}
		//返回
		return $html;
	}

	/**
	 * 确认
	 */
	public function confirmEdit()
	{
		$id    = $this->post('id');
		$info  = query(self::table, " coid = '" . self::$coid . "' AND id = '$id'");
		$field = [
			'state'       => '已确认',
			'confirmTime' => $this->time,
		];
		if (!$this->power(self::page, 'confirm')) {
			$json['warn'] = '你还没有确认权限';
		} elseif (empty($info['id'])) {
			$json['warn'] = '未找到此入库单';
		} elseif ($info['state'] != '待确认') {
			$json['warn'] = '此入库单不是待确认状态，不能确认';
		} else {
			$this->startTrans();
			$isPass       = true; // 事务通过标志
			$json['warn'] = static::update([
				"table" => self::table,
				"field" => $field,
				"where" => "id = '$info[id]'",
			]);
			if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass === true) {
				$details = find([
					'table' => self::tableMx,
					'where' => " orderId = '{$info['id']}'",
				]);
				foreach ($details['array'] as $key => $value) {
					static::insert([
						'table' => self::tableRecord,
						'field' => [
							'id'            => self::getNo(),
							'coid'          => self::$coid,
							'warehouseId'   => $info['warehouseId'],
							'mdid'          => $value['mdid'],
							'num'           => $value['num'],
							'inventoryId'   => $info['id'],
							'inventoryMxId' => $value['id'],
						],
					]);
				}
				$this->commitTrans();//提交事务
				auditingFollow([
					"type"   => "模具入库",
					"typeId" => $info['id'],
					"text"   => "【{$this->control['name']}】确认",
				]);
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
			}
		}
		resp:
		return json_encode($json, 320);
	}

	/**
	 * 取消
	 */
	public function cancelEdit()
	{
		$id    = $this->post('id');
		$info  = query(self::table, " coid = '" . self::$coid . "' AND id = '$id'");
		$field = [
			'state'      => '制单',
			'commitTime' => '',
		];
		if (!$this->power(self::page, 'cancel')) {
			$json['warn'] = '你还没有取消权限';
		} elseif (empty($info['id'])) {
			$json['warn'] = '未找到此入库单';
		} elseif ($info['state'] == '已确认') {
			$json['warn'] = '此入库单是已确认状态，无法取消';
		} else {
			$json['warn'] = static::update([
				"table" => self::table,
				"field" => $field,
				"where" => "id = '$info[id]'",
			]);
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				auditingFollow(array(
					"type"   => "模具入库",
					"typeId" => $info['id'],
					"text"   => "【{$this->control['name']}】取消",
				));
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
			}
		}
		resp:
		return json_encode($json, 320);
	}

	/**
	 * 提交
	 */
	public function commitEdit()
	{
		$id    = $this->post('id');
		$info  = query(self::table, " coid = '" . self::$coid . "' AND id = '$id'");
		$field = [
			'state'      => '待确认',
			'commitTime' => $this->date,
		];
		if (!$this->power(self::page, 'edit')) {
			$json['warn'] = '你还没有编辑权限';
		} elseif (empty($info['id'])) {
			$json['warn'] = '未找到此入库单';
		} elseif ($info['state'] != '制单') {
			$json['warn'] = '此入库单不是制单状态，不能提交';
		} else {
			$json['warn'] = update(array(
				"table" => self::table,
				"field" => $field,
				"where" => "id = '$info[id]'",
			));
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				auditingFollow([
					"type"   => "模具入库",
					"typeId" => $info['id'],
					"text"   => "【{$this->control['name']}】提交",
				]);
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
			}
		}
		resp:
		return json_encode($json, 320);
	}

	// 操作中转
	public function operate()
	{
		$act  = $this->post('act') ?? '';
		$pwd  = $word = false; // 需要密码
		$form = $power = '';
		switch ($act) {
			case 'confirm':
				$act      = 'confirm';
				$msg      = '确认';
				$title    = '是否确认此入库单，确认后将不可修改？';
				$function = 'confirmEdit';
				$form     = self::page . 'OperateForm, detailForm';
				$power    = '';
				$word     = true;
				break;
			case 'commit':
				$act      = 'edit';
				$msg      = '编辑';
				$title    = '是否确认提交此入库单？';
				$function = 'commitEdit';
				$form     = self::page . 'OperateForm, detailForm';
				$power    = '';
				$word     = true;
				break;
			case 'cancel':
				$act      = 'cancel';
				$msg      = '撤回';
				$title    = '是否确认取消此入库单？';
				$function = 'cancelEdit';
				$form     = self::page . 'OperateForm, detailForm';
				$power    = '';
				$word     = true;
				break;
			default:
				$act      = 'del';
				$msg      = '删除' . self::title;
				$title    = self::page . 'Delete';
				$function = 'delete';
				$form     = self::page . 'OperateForm, listForm, quoForm';
				$power    = '';
				break;
		}
		if (!$this->power(self::page, $act)) {
			$_SESSION['warn'] = '你还没有' . $msg . '的权限';
			$json             = [
				'warn' => 2,
				'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
			];
		} else {
			return $this->confirm([
				'title'    => $title,
				'function' => $function,
				'form'     => $form,
				'power'    => $power,
				'pwd'      => $pwd,
				'word'     => $word,
			]);
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * 删除
	 *
	 * @return bool|string
	 */
	public function delete()
	{
		$array = $this->post('listId') ?? $this->post('id');
		if (!$this->power(self::page, "del")) {
			$json['warn'] = "你没有删除的权限";
		} elseif (empty($array)) {
			$json['warn'] = "你一个数据都没有选择呢";
		} else {
			$text  = "";
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			foreach ($array as $id) {
				$info = query(self::table, " coid = '" . self::$coid . "' AND id = '$id' ");
				if ($info['state'] == '已确认') {
					$warn = "删除失败：已确认，暂不能删除";
				} else {
					//最后删除基本参数
					delete(array("table" => self::table, "where" => " id = '$id' "));
					delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
					delete(array("table" => 'auditing_follow', "where" => " typeId = '$id' "));
					//返回
					$warn = "删除成功";
					$x++;
				}
				$text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
			}
			//添加日志
			$text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
			$this->logText(array("type" => self::page, "text" => $text));
			$_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
			$json['warn']     = 2;
			$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
		}
		return json_encode($json, 320);
	}

	/**
	 * 批量打印
	 *
	 * @return string
	 */
	public function batchPrint(): string
	{
		$lists = $this->get('lists');
		if(empty($lists)){
			exit('参数错误');
		}else{
			$listId = base64_decode($lists, true);
			$array = explode(',', $listId);
			$data = [];
			foreach ($array as $id){
				$data[] = static::printPage($id, false);
			}
			return (new printTemplateClass())->start(self::page, $data);
		}
	}

	/**
	 * 打印
	 *
	 * @return string
	 */
	public function printPage($param = '', $isReturn = true): string|array
	{
		$id                  = $param ?: $this->get('id');
		$info                = query(self::table, " id = '$id'");
		$info['companyName'] = query('company', "coid = '" . self::$coid . "'")['name']; //公司名称//公司名称
		$info['title']       = self::title;
		$info['printTime']   = $this->time;
		$info['stid']        = self::findStaff($info['stid']);
		$info['targetId']    = query('supplier', "id = '$info[targetId]'")['name'];
		$info['warehouseId'] = query('warehouse', "id = '$info[warehouseId]'")['name'];
		$info['qr']          = "source=" . self::page . "&id=" . $info['id'];
		$detail              = find(['table' => self::tableMx, 'where' => " orderId = '$info[id]' order by time asc"])['array'];
		$items               = [];
		$x                   = 1;
		$totalNum            = $totalPrice = $totalMoney = 0;
		foreach ($detail as $array) {
			$mold    = query(self::tableTarget, "id = '$array[mdid]'");
			$total   = self::formattingFigure($array['price'] * $array['num']);
			$items[] = [
				'no'    => $x,
				'code'  => $mold['code'],
				'name'  => $mold['name'],
				'model' => $mold['model'],
                'num'   => self::lostZero($array['num'],'numPrecision'),
                'price' => self::lostZero($array['price'],'pricePrecision'),
                'money' => self::lostZero($total),
				'text'  => $array['text'],
			];
			$x++;
			$totalPrice += $array['price'];
			$totalMoney += $total;
			$totalNum   += $array['num'];
		}
		$append         = [
			'no'    => '合计',
            'num'   => self::lostZero($totalNum,'numPrecision'),
            'price' => self::lostZero($totalPrice,'pricePrecision'),
            'money' => self::lostZero($totalMoney),
		];
		$items[]        = $append;
		$info['detail'] = $items;
		if ($isReturn) {
			return (new printTemplateClass())->start(self::page, $info);
		} else {
			return $info;
		}
	}

}
